const fs = require('fs')

const userinfoService = require('../service/userinfo.service')
const fileService = require('../service/file.service')
const {AVATAR_PATH} = require('../contants/file-path')

class UserinfoController {
  // 获取用户信息
  async getUserinfo(ctx, next) {
    const userId = ctx.params.userId
    try {
      const result = await userinfoService.getInfoById(userId)
      if(result) {
        ctx.success({
          data: result[0]
        })
      }
    } catch (error) {
      console.log(error.message)
      return
    }
  }
  // 修改用户昵称
  async rename(ctx, next) {
    const userId = ctx.user.id
    const newName = ctx.request.body.newName
    try {
      const result = await userinfoService.rename(userId, newName)
      if(result) {
        ctx.success({
          msg: '重命名成功'
        })
      }
    } catch (error) {
      console.log(error.message)
      return
    }
  }
  // 修改用户信息: age gender birthday location 
  async edit(ctx, next) {
    const userId = ctx.user.id
    const userinfo = ctx.request.body
    const age = userinfo.age || null
    const gender = userinfo.gender || null
    const birthday = userinfo.birthday || null
    const location = userinfo.location || null
    try {
      const result = await userinfoService.editUserinfo(userId, age, gender, birthday, location)
      if(result) {
        ctx.success({
          msg: '编辑成功'
        })
      }
    } catch (error) {
      console.log(error.message)
      return
    }
  }
  // 获取用户头像
  async getAvatar(ctx, next) {
    const userId = ctx.params.userId
    const avatarInfo = await fileService.getAvatarById(userId)

    ctx.response.set('content-type', avatarInfo.mimetype)
    ctx.body = fs.createReadStream(`${AVATAR_PATH}/${avatarInfo.filename}`)
  }
}

module.exports = new UserinfoController()